package com.xiannimei.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiannimei.web.TimeIntervalCookie;

public class CookieUtil {

	private static final Logger log = LoggerFactory.getLogger(CookieUtil.class);
	
	public static String getCookieValue(String name, HttpServletRequest request) {
      log.debug("[get Cookie {}]", name);
      String value = null;
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
          for (Cookie cookie : cookies) {
//              log.info("All Cookies:" + cookie.getName() + "," + cookie.getValue());
              if (cookie.getName().equals(name)) {
                  if (cookie.getValue() != null && !cookie.getValue().equals("")) {
                      value = cookie.getValue();
                      break;
                  }
              }

          }
      }
      log.debug("[Cookie {}] {}", name, value);
      return value;
  }

  public static void setCookieValue(String name,String value, HttpServletResponse response){
      log.debug("[set Cookie {}] {}",name ,value);
      response.addCookie(new TimeIntervalCookie(name,value));
  }
  
  public static void setCookieValue(String name,String value, HttpServletResponse response, int interval){
      log.debug("[set Cookie {}] {}",name ,value);
      response.addCookie(new TimeIntervalCookie(name,value, interval));
  }
}
